package com.liaogui.redis.component;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.core.RedisTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 基于bitmap的布隆过滤器
 * @author liaogui
 * @date 2025/3/2 21:57
 */
@Component
public class RedisBloomFilter {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String BLOOM_FILTER_KEY = "bloom_filter:";

    private static final int BLOOM_FILTER_SIZE = 1000;

    private List<SimpleHash> hashFunctions;
    /**
     * 多个哈希函数的种子
     */
    private static final int[] HASH_SEEDS = {3, 5, 7, 11, 13, 17};

    public RedisBloomFilter() {
        this.hashFunctions = new ArrayList<>();
        for (int hashSeed : HASH_SEEDS) {
            hashFunctions.add(new SimpleHash(BLOOM_FILTER_SIZE, hashSeed));
        }
    }


    /**
     * 添加元素到布隆过滤器
     *
     * @param value 价值
     */
    public void add(String value) {
        for (SimpleHash hashFunction : hashFunctions) {
            redisTemplate.opsForValue().setBit(BLOOM_FILTER_KEY + value, hashFunction.hash(value), true);
        }
    }

    /**
     * 检查元素是否存在布隆过滤器中
     *
     * @param value 价值
     * @return boolean
     */
    public boolean contains(String value) {
        for (SimpleHash hashFunction : hashFunctions) {
            if (!Boolean.TRUE.equals(redisTemplate.opsForValue().getBit(BLOOM_FILTER_KEY, hashFunction.hash(value)))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 静态内部类
     *
     * @author liaogui
     * @date 2025/03/03
     */
    public static class SimpleHash {
        private int cap;

        private int seed;

        public SimpleHash(int cap, int seed) {
            this.cap = cap;
            this.seed = seed;
        }

        public int hash(String value) {
            int result = 0;
            byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
            for (byte b : bytes) {
                // 累加计算哈希值
                result = seed * result + b;
            }
            return (cap - 1) & result;
        }
    }
}
